/****************************************************
          File Name:35-2.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 02 Sep 2014 04:38:25 PM CST
*****************************************************/

#include<stdio.h>
#include<string.h>
#include<sched.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>

void err(int eRR, char *fun)
{
    if(eRR==-1)
    {
        perror(fun);
        exit(errno);
    }
}

int main(int argc,char *argv[])
{
    pid_t pid;
    int res;
    struct sched_param pa;

    if(argc<2 || strcmp(argv[1],"--help")==0)
    {
        fprintf(stderr,"%s %s\n",argv[0],"-[set|get] (policy)[r|f|o] (priority)[1~99] pid ...  ");
        printf("schedulers:\n");
        printf("SCHED_RR: %d\nSCHED_FIFO: %d\nSCHED_OTHER: %d\n",SCHED_RR,SCHED_FIFO,SCHED_OTHER);
        printf("************************************\n");
        exit(1);
    }

    if(strcmp(argv[1],"-set")==0)
    {
        pid=atoi(argv[4]);
        pa.sched_priority=atoi(argv[3]);

        switch(argv[2][0])
        {
            case 'r':
                res=sched_setscheduler(pid,SCHED_RR,&pa);
                err(res,"setschedduler");
                break;
            case 'f':
                res=sched_setscheduler(pid,SCHED_FIFO,&pa);
                err(res,"setschedduler");
                break;
            case 'o':
                res=sched_setscheduler(pid,SCHED_OTHER,&pa);
                err(res,"setschedduler");
                break;
        }
    }
    else if(strcmp(argv[1],"-get")==0)
    {
       pid=atoi(argv[2]);
       res=sched_getscheduler(pid); 
       sched_getparam(pid,&pa);
       printf("the sched is: %s\n policy is: %d\n",res==0?"OTHER":(res==1)?"FIFO":"RR"
               ,pa.sched_priority);
    }
    exit(0);
}
